import uuid
import datetime

from common.models import TbReview
from manager.serializer import ReviewSerializers


class ReviewProcessor:
    review = TbReview.objects

    def add_review(self, **kwargs):
        """
        提交一个审核
        """
        review_type = kwargs.get("review_type")
        user = kwargs.get("user")
        review_info = {
            "uid": uuid.uuid1().hex,
            "create_user": user.username,
            "create_user_id": user.uid,
            "create_time": datetime.datetime.now(),
            "is_delete": 0,
            "review_status": 0,
            "review_type": review_type,
            "add_review_date": datetime.datetime.now(),
            "is_finished": 0
        }
        review_ser = ReviewSerializers(data=review_info)
        if review_ser.is_valid():
            review = review_ser.save()
        else:
            raise ValueError(review_ser.errors)
        return review

    def get_review_list(self):
        """
        获取审核列表
        """
        return TbReview.objects.filter(is_delete=0).order_by("-create_time")

    def get_review_status(self, review_id):
        """
        获取审核状态
        """
        review = TbReview.objects.get(uid=review_id)
        review_ser = ReviewSerializers(instance=review)
        return review_ser.data

    def process_reviews(self, **kwargs):
        """
        处理审核
        """
        # 取参
        # --- start ---
        review_id = kwargs.get("review_id")
        review_status = kwargs.get("review_status")
        rejection_reason = kwargs.get("rejection_reason")
        # --- end ---
        try:
            review = TbReview.objects.get(uid=review_id)
        except TbReview.DoesNotExist:
            raise ValueError("未找到该条审核")
        if review.is_finished is not 0:
            raise ValueError("该条审核已经处理了")
        review.review_status = review_status
        review.rejection_reason = rejection_reason
        review.is_finished = 1
        review.save()
        return review
